﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Skybot.CoordConverts
{

    /// <summary>
    /// http://blog.woodbunny.com/post-68.html
    /// 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法
    ///百度google坐标互转
    /// </summary>
    /// <remarks>算法代码如下，其中 bd_encrypt 将 GCJ-02 坐标转换成 BD-09 坐标， bd_decrypt 反之。</remarks>
    public class BaiduCoordConveter
    {
        private const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

        /// <summary>
        /// 加密 google坐标 -> 百度坐标
        /// </summary>
        /// <param name="gg_lat">google坐标纬度</param>
        /// <param name="gg_lon">google坐标经度</param>
        /// <param name="bd_lat">百度坐标纬度</param>
        /// <param name="bd_lon">百度坐标经度</param>
        public static void BdEncrypt(double gg_lat, double gg_lon, out double bd_lat, out double bd_lon)
        {
            double x = gg_lon, y = gg_lat;
            double z = Math.Sqrt(x * x + y * y) + 0.00002 * Math.Sin(y * x_pi);
            double theta = Math.Atan2(y, x) + 0.000003 * Math.Cos(x * x_pi);
            bd_lon = z * Math.Cos(theta) + 0.0065;
            bd_lat = z * Math.Sin(theta) + 0.006;
        }

        /// <summary>
        /// 解密 百度坐标->google坐标
        /// </summary>
        /// <param name="bd_lat">百度坐标纬度</param>
        /// <param name="bd_lon">百度坐标经度</param>
        /// <param name="gg_lat">google坐标纬度</param>
        /// <param name="gg_lon">google坐标经度</param>
        public static void BdDecrypt(double bd_lat, double bd_lon, out double gg_lat, out double gg_lon)
        {
            double x = bd_lon - 0.0065, y = bd_lat - 0.006;
            double z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * x_pi);
            double theta = Math.Atan2(y, x) - 0.000003 * Math.Cos(x * x_pi);
            gg_lon = z * Math.Cos(theta);
            gg_lat = z * Math.Sin(theta);
        }
    }
}